package com.blockchain.console.service.user.achieve;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;

import com.blockchain.console.config.ConsoleConst;
import com.blockchain.console.service.AbstractConsoleService;
import com.blockchain.framework.data.sql.SQLConnectionProvider;
import com.blockchain.framework.resource.ResourceNotFoundException;
import com.blockchain.framework.service.ServiceResource;
import com.blockchain.framework.service.query.ItemParser;

public abstract class AbstractUserService extends AbstractConsoleService {

	public AbstractUserService(ServiceResource serviceResource) {
		super(serviceResource);
	}

	protected SQLConnectionProvider getSQLConnectionProvider()
			throws ResourceNotFoundException, SQLException {
		return serviceResource.getDataConnectionProvider(
				SQLConnectionProvider.class, ConsoleConst.DB_MASTER_PROVIDER);
	}

	protected Connection getConnection() throws ResourceNotFoundException,
			SQLException {
		return serviceResource.getDataConnectionProvider(
				SQLConnectionProvider.class, ConsoleConst.DB_MASTER_PROVIDER)
				.getConnection(ConsoleConst.DB_CONSOLE);
	}

	protected Connection getConnection(String db)
			throws ResourceNotFoundException, SQLException {
		return serviceResource.getDataConnectionProvider(
				SQLConnectionProvider.class, ConsoleConst.DB_MASTER_PROVIDER)
				.getConnection(db);
	}
	
	protected String selectString(Connection connection, String sql,
			Object... paramters) throws SQLException {
		final String decimal = "";
		return select(connection, new ItemParser<String>() {
			@Override
			public String parse(ResultSet resultSet) throws SQLException {
				if (resultSet.next()) {
					return resultSet.getString(1);
				}
				return decimal;
			}
		}, sql, paramters);
	}
	
	protected Integer selectInt(Connection connection, String sql,
			Object... paramters) throws SQLException {
		final Integer decimal = new Integer(0);
		return select(connection, new ItemParser<Integer>() {
			@Override
			public Integer parse(ResultSet resultSet) throws SQLException {
				if (resultSet.next()) {
					return resultSet.getInt(1);
				}
				return decimal;
			}
		}, sql, paramters);
	}
	
	protected BigDecimal selectBigDecimal(Connection connection, String sql,
			Object... paramters) throws SQLException {
		final BigDecimal decimal = new BigDecimal(0);
		return select(connection, new ItemParser<BigDecimal>() {
			@Override
			public BigDecimal parse(ResultSet resultSet) throws SQLException {
				if (resultSet.next()) {
					return resultSet.getBigDecimal(1);
				}
				return decimal;
			}
		}, sql, paramters);
	}
	protected static final DecimalFormat AMOUNT_SPLIT_FORMAT = new DecimalFormat(
			"0.00");
	protected String format(BigDecimal amount) {
		if (amount == null) {
			return "0";
		}
		return AMOUNT_SPLIT_FORMAT.format(amount);
	}
}
